package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Host;

public class MetricPktsManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;
	
	public MetricPktsManage(DBConn db)
	{
		this.db=db;
	}
	public MetricPktsManage(DBPool db)
	{
		this.dbpool=db;
	}
	
	public ResultSet getData(int HostID)
	{
		String sql="select * from Metric_PKTS where HostID="+HostID+" order by CollectTime desc LIMIT 1";
		//System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public ResultSet getData(int HostID,String start,String end)
	{
		String sql="select * from Metric_PKTS where CollectTime>'"+start+"' and CollectTime<'"+end+"' and HostID="+HostID+" order by collectTime asc";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String addRecord(int HostID,Host host,String collectTime)
	{
		float bytes_in=Float.parseFloat(host.getMetric("bytes_in"));
		float bytes_out=Float.parseFloat(host.getMetric("bytes_out"));
		float pkts_in=Float.parseFloat(host.getMetric("pkts_in"));
		float pkts_out=Float.parseFloat(host.getMetric("pkts_out"));
		
		String sql="insert into Metric_PKTS (HostID,bytes_in,bytes_out,pkts_in,pkts_out,CollectTime) values ("+HostID+","+bytes_in+","+bytes_out+","+pkts_in+","+pkts_out+",'"+collectTime+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		} catch (Exception e)
		{
			return "Fail";
		}
	}

	public String deleteRecord(int HostID)
	{
		String sql="delete from Metric_PKTS where HostID="+HostID;
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(String start,String end)
	{
		String sql="delete from Metric_PKTS where CollectTime>'"+start+"' and CollectTime<'"+end+"'";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
